//
//  HMHTTPManager.m
//  HuanMai
//
//  Created by Magician on 2018/3/20.
//  Copyright © 2018年 LinkWheat. All rights reserved.
//

#import "CNHTTPManager.h"


#define kTimeOut 60.0f



@interface CNHTTPManager ()


@end

@implementation CNHTTPManager

+ (instancetype)shared {
    static CNHTTPManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[CNHTTPManager alloc] init];
    });
    return instance;
}

- (instancetype)init {
    if (self = [super init]) {
                
        self.sessionManager = [AFHTTPSessionManager manager];
        
        // Request
        self.sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        [self.sessionManager.requestSerializer setValue:@"application/json"
                                     forHTTPHeaderField:@"Content-Type"];
        [self.sessionManager.requestSerializer setValue:@"app"
                                     forHTTPHeaderField:@"client"];
        [self.sessionManager.requestSerializer setValue:@"iOS"
                                     forHTTPHeaderField:@"appPlat"];
        [self.sessionManager.requestSerializer setValue:@"AppStore"
                                     forHTTPHeaderField:@"channel"];
//        [self.sessionManager.requestSerializer setValue:[ZGComFunc getAppVersion]
//                                     forHTTPHeaderField:@"appVersion"];
//        [self.sessionManager.requestSerializer setValue:[ZGComFunc getDeviceId]
//                                     forHTTPHeaderField:@"deviceCode"];
        
        NSString *token = [[NSUserDefaults standardUserDefaults] stringForKey:@"token"];
        if (token) {
            [self.sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
        }
        
        [self.sessionManager.requestSerializer setTimeoutInterval:kTimeOut];

        // Response
        AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
        response.removesKeysWithNullValues = YES;
        response.acceptableContentTypes = [NSSet setWithObjects:
                                           @"application/json",
                                           @"text/html",
                                           @"text/json",
                                           @"text/javascript",
                                           @"text/plain", nil];
        self.sessionManager.responseSerializer = response;
        
    }
    return self;
}



- (void)POST:(NSString *)URLString
  parameters:(NSDictionary *)parameters
     success:(CNRequestSuccessBlock)success
     failure:(CNRequestFailureBlock)failure {
    NSString *token = [[UserInfoManager shareInstance] getUserInfo].token;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (token) {
        [dic setObject:token forKey:@"token"];
    }
    [dic addEntriesFromDictionary:parameters];
    self.operationQueue = self.sessionManager.operationQueue;
    NSString *absoluteURL = [kServerURL stringByAppendingString:@"/"];
    absoluteURL = [absoluteURL stringByAppendingString:URLString];
    if (token.length > 0) {
        absoluteURL = [NSString stringWithFormat:@"%@?token=%@",absoluteURL,token];
    }
    [self.sessionManager POST:absoluteURL parameters:dic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        !success ? : success(responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *resp = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode = resp.statusCode;

                
        // 错误描述
        NSString *errorStr = kDefultErrorMsg;
  
        !failure ? : failure(error, errorStr);
    }];

}

- (void)GET:(NSString *)URLString
 parameters:(NSDictionary *)parameters
    success:(CNRequestSuccessBlock)success
    failure:(CNRequestFailureBlock)failure {
    
    NSString *token = [[UserInfoManager shareInstance] getUserInfo].token;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (token) {
        [dic setObject:token forKey:@"token"];
    }
    [dic addEntriesFromDictionary:parameters];
    self.operationQueue = self.sessionManager.operationQueue;
    
    NSString *absoluteURL = [kServerURL stringByAppendingString:@"/"];
    absoluteURL = [absoluteURL stringByAppendingString:URLString];

    [self.sessionManager GET:absoluteURL parameters:dic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        !success?:success(responseObject);
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        !failure?:failure(error,kDefultErrorMsg);
    }];

}

/**
 *取消当前请求队列的所有请求
 */
- (void)cancelAllOperations{
    if (self.operationQueue) {
        [self.operationQueue cancelAllOperations];
    }
}

/**
 监听网络状态,网络状态
 */
+ (void)listenNetworkStatus:(void(^)(AFNetworkReachabilityStatus status))networkStatus
{
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [reachabilityManager startMonitoring];
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (networkStatus) {
            networkStatus(status);
        }
    }];
}

@end


@implementation CNResponseDataModel

@end



